<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<div v-show="showSearch">
				<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList" class="search-form-row">
					<el-row :gutter="10">
						<el-col :span="6">
							<el-form-item label="产品分类:" prop="category">
								<el-select v-model="state.queryForm.category" placeholder="请选择产品分类">
									<el-option v-for="(item, index) in categoryData" :key="index" :label="item.name" :value="item.identify"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="产品名称:" prop="name">
								<el-input v-model="state.queryForm.name" placeholder="请输入产品名称" />
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="发布状态:" prop="isPublish">
								<el-select v-model="state.queryForm.isPublish" placeholder="请选择状态">
									<el-option label="已发布" value="1" />
									<el-option label="未发布" value="0" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item>
								<el-button formDialogRef icon="search" type="primary" @click="getDataList">查询</el-button>
								<el-button formDialogRef icon="Refresh" @click="resetQuery">重置</el-button>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
			<el-row>
				<div class="mb10" style="width: 100%">
					<el-button class="ml10" icon="folder-add" v-auth="'access_accessProduct_add'" type="primary" @click="formDialogRef.openDialog(null, 'add')">
						新增
					</el-button>
					<!-- <el-button class="ml10" icon="upload-filled" plain type="primary" @click="excelUploadRef.show()"> 导入 </el-button> -->
					<el-button
						class="ml10"
						icon="Delete"
						v-auth="'access_accessProduct_del'"
						:disabled="multiple"
						type="primary"
						@click="handleDelete1(selectObjs)"
					>
						删除
					</el-button>
					<right-toolbar
						v-model:showSearch="showSearch"
						v-auth="'access_accessProduct_view'"
						:export="'access_accessProduct_export'"
						class="ml10"
						style="float: right; margin-right: 20px"
						@queryTable="getDataList"
						@exportExcel="exportExcel"
					>
						<el-tooltip effect="dark" content="卡片模式" placement="top">
							<el-button v-show="cardType === 'card'" circle icon="Grid" @click="cardType === 'card' ? (cardType = 'table') : (cardType = 'card')" />
						</el-tooltip>
						<el-tooltip effect="dark" content="列表模式" placement="top">
							<el-button v-show="cardType === 'table'" circle icon="List" @click="cardType === 'card' ? (cardType = 'table') : (cardType = 'card')" />
						</el-tooltip>
					</right-toolbar>
				</div>
			</el-row>
			<!-- 列表 -->
			<el-table
				v-loading="state.loading"
				:data="state.dataList"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
				class="tableClass"
				@selection-change="handleSelectionChange"
				v-show="cardType === 'table'"
			>
				<el-table-column type="selection" width="40" />
				<el-table-column type="index" label="序号" width="100" />
				<el-table-column prop="name" label="产品名称" width="300" />

				<el-table-column prop="supplierName" label="供应商" width="250" />
				<el-table-column prop="categoryName" label="品类" />
				<el-table-column prop="accessWay" label="接入方式" />
				<el-table-column prop="isPublish" label="状态">
					<template #default="scope">
						<span>{{ scope.row.isPublish == 1 ? '已发布' : '未发布' }}</span>
					</template>
				</el-table-column>
				<el-table-column fixed="right" label="操作" width="500" align="center">
					<template #default="scope">
						<el-button icon="view" text type="primary" @click="formDialogRef.openDialog(scope.row, 'detail')">详情 </el-button>
						<el-button icon="edit-pen" text type="primary" @click="formDialogRef.openDialog(scope.row, 'edit')">修改 </el-button>
						<el-button icon="operation" text type="primary" @click="openObjectModel(scope.row)">物模型 </el-button>
						<el-button icon="switch" text type="primary" @click="goto(scope.row.flowId)">数据流转 </el-button>
						<el-button icon="tools" text type="primary" @click="openDeviceList(scope.row)">设备管理 </el-button>
						<el-button icon="delete" text type="primary" @click="handleDelete(scope.row.id)">删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 卡片 -->
			<div v-show="cardType === 'card'" class="cardClass">
				<el-card v-loading="state.loading" class="card" shadow="hover" v-for="item in state.dataList" :key="item.id">
					<el-row class="cardRow">
						<span class="cardTitle">{{ item.name }}</span>
					</el-row>
					<el-row>
						<el-col :span="16" class="card-main">
							<el-row class="cardRow">
								<span>品类：{{ item.categoryName }}</span>
							</el-row>

							<el-row class="cardRow">
								<span>接入方式：{{ item.accessWay }}</span>
							</el-row>
							<el-row class="cardRow">
								<span>状态：{{ item.isPublish == 1 ? '已发布' : '未发布' }}</span>
							</el-row>
						</el-col>
						<el-col :span="8">
							<el-row>
								<div style="height: 100px; width: 100px">
									<img v-if="item.img" :src="baseURL + item.img" width="100px" height="100px" style="max-height: 100%" alt="" />
									<img v-else src="/@/assets/pic_device.png" width="100px" height="100px" alt="" />
								</div>
							</el-row>
						</el-col>
						<el-row class="">
							<span
								>供应商：<el-tooltip :content="item.supplierName" placement="top"
									><span>{{ item.supplierName }}</span></el-tooltip
								></span
							>
						</el-row>
					</el-row>

					<template #footer>
						<div class="cardFooter">
							<el-button link type="primary" @click="formDialogRef.openDialog(item, 'detail')">详情 </el-button>
							<el-button link type="primary" @click="formDialogRef.openDialog(item, 'edit')">修改 </el-button>
							<el-button link type="primary" @click="openObjectModel(item)">物模型 </el-button>
							<el-button link type="primary" @click="goto(item.flowId)">数据流转 </el-button>
							<el-button link type="primary" @click="openDeviceList(item)">设备管理 </el-button>
							<el-button link type="primary" @click="handleDelete(item.id)">删除 </el-button>
						</div>
					</template>
				</el-card>
			</div>
			<pagination v-bind="state.pagination" @size-change="sizeChangeHandle" @current-change="currentChangeHandle" />
			<!-- 编辑、新增  -->
			<form-dialog
				ref="formDialogRef"
				@refresh="getDataList(false)"
				:categoryData="categoryData"
				:supplierData="supplierData"
				:nodeTypeData="product_node_type"
				:accessWayData="product_access_way"
			/>
			<!-- 物模型 -->
			<object-model ref="objectModelRef" />
			<!-- 设备管理 -->
			<el-dialog v-model="visible" :close-on-click-modal="false" title="设备列表" draggable width="60%">
				<el-table v-loading="loading" :data="devicesList">
					<el-table-column type="index" label="序号" width="100" />
					<el-table-column prop="unitNo" label="设备ID" width="300" />
					<el-table-column prop="deviceName" label="设备名称" />
					<el-table-column prop="productName" label="所属产品" />
					<el-table-column prop="onlineStatus" label="状态">
						<template #default="scope">
							<span v-if="scope.row.onlineStatus === 1" type="success">在线</span>
							<span v-else type="danger">离线</span>
						</template>
					</el-table-column>
					<el-table-column prop="createTime" label="创建时间" />
				</el-table>
				<pagination v-bind="page" @size-change="sizeChange" @current-change="currentChage" />
			</el-dialog>
			<!-- 批量新增产品 -->
			<!-- <upload-excel
			ref="excelUploadRef"
			title="产品信息导入"
			temp-url="/admin/sys-file/local/file/product.xlsx"
			temp-name="产品模板.xlsx"
			url="/admin/accessProduct/import"
			@refreshDataList="getDataList"
		/> -->
		</div>
	</div>
</template>

<script lang="ts" name="product" setup>
import { fetchList, delObjs, addObj, editObj } from '/@/api/basiciot/device/product';
import { fetchList as getCategoryList } from '/@/api/basiciot/device/category';
import { fetchList as getDevicesList } from '/@/api/basiciot/device/device';
import { fetchList as getSupplierList } from '/@/api/basiciot/device/supplier';
import { onMounted, reactive, ref } from 'vue';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { BasicTableProps, useTable } from '/@/hooks/table';
import { useDict } from '/@/hooks/dict';
import { useI18n } from 'vue-i18n';

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const ObjectModel = defineAsyncComponent(() => import('./objectModel.vue'));

const { t } = useI18n();

const cardType = ref('card');
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: fetchList,
	createdIsNeed: false,
	pagination: {
		current: 1,
		size: 12,
		total: 0,
	},
});
//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, downBlobFile, tableStyle } = useTable(state);
// 清空搜索条件
const resetQuery = () => {
	queryRef.value.resetFields();
	getDataList();
};
const visible = ref(false);
const devicesList = ref([]);
const loading = ref(false);
const page = reactive({
	total: 0, // 总页数
	currentPage: 1, // 当前页数
	pageSize: 10, // 每页显示多少条
});
const productKey = ref('');
const formDialogRef = ref();
const showSearch = ref(true);
const queryRef = ref();
//获取接入类型 和接入方式的字典数据
const { product_access_way, product_node_type } = useDict('product_access_way', 'product_node_type');
//获取产品品类关联数据
const categoryData: any = ref([]);
const supplierData = ref([]);
const excelUploadRef = ref();
const multiple = ref(true);
// 多选rows
const selectObjs = ref([]) as any;
// 删除操作
const handleDelete = (id: string) => {
	useMessageBox()
		.confirm(t('common.delConfirmText'))
		.then(() => {
			delObjs([id])
				.then(() => {
					getDataList();
					useMessage().success(t('common.delSuccessText'));
				})
				.catch((err: any) => {
					useMessage().error(err.msg);
				});
		});
};
const handleDelete1 = (ids: Array<string>) => {
	useMessageBox()
		.confirm(t('common.delConfirmText'))
		.then(() => {
			delObjs(ids)
				.then(() => {
					getDataList();
					useMessage().success(t('common.delSuccessText'));
				})
				.catch((err: any) => {
					useMessage().error(err.msg);
				});
		});
};
//物模型弹窗
const objectModelRef = ref();
const openObjectModel = (row: any) => {
	objectModelRef.value.getInfo(row.productKey);
};

//设备列表弹窗
const openDeviceList = (row: any) => {
	visible.value = true;
	loading.value = true;
	page.currentPage = 1;
	productKey.value = row.productKey;
	getList(productKey.value, page);
};
const getList = (key: string, page: any) => {
	getDevicesList({ productKey: key, current: page.currentPage, size: page.pageSize })
		.then((res) => {
			devicesList.value = res.data.records;
			page.total = res.data.total;
		})
		.catch((err: any) => {
			useMessage().error(err.msg);
		})
		.finally(() => {
			loading.value = false;
		});
};
const sizeChange = (val: number) => {
	page.pageSize = val;
	getList(productKey.value, page);
};
const currentChage = (val: number) => {
	page.currentPage = val;
	getList(productKey.value, page);
};
// 导出excel
const exportExcel = () => {
	downBlobFile('/admin/accessProduct/export', Object.assign(state.queryForm), '产品列表.xlsx');
};
// 多选事件
const handleSelectionChange = (objs: { id: string }[]) => {
	selectObjs.value = objs.map(({ id }) => id);
	multiple.value = !objs.length;
};
onMounted(() => {
	getDataList();
	getCategoryList({ current: 1, size: 9999 }).then((res) => {
		categoryData.value = res.data.records;
	});
	getSupplierList({ currentPage: 1, pageSize: 9999 }).then((res) => {
		supplierData.value = res.data.records || [];
	});
});
const goto = (id: string) => {
	window.open('http://222.71.249.42:1880/#flow/' + id, '_blank');
};
</script>
<style scoped lang="scss">
.tableClass {
	min-height: vh(580);
}

.cardClass {
	min-height: vh(580);
	display: flex;
	flex-wrap: wrap;
	overflow-y: scroll;

	.card {
		width: 24%;
		height: 240px;
		margin: 0 15px 15px 0;
	}

	.cardRow {
		margin-bottom: 10px;

		img {
			max-height: 100%;
		}
	}

	.cardTitle {
		font-size: 16px;
		font-weight: 600;
	}

	.cardFooter {
		display: flex;
		justify-content: space-between;
	}
}
</style>
